import datetime

from webapp.extensions import AppException
from webapp.models import VExamInfo, VCourse, Session, Room, ExamInfoTable, db, Grade


class ExamInfoService:
    @staticmethod
    def query_all(page=0, size=9999, **kwargs) -> list:
        create_times = kwargs.get('createTime')
        start_time = kwargs.get('start')
        ename = kwargs.get('ename')
        courseId = kwargs.get('courseId')
        sessionId = kwargs.get('sessionId')
        query = []
        if courseId:
            query.append(VExamInfo.courseId == courseId)
        if sessionId:
            query.append(VExamInfo.sessionId == sessionId)
        if ename:
            query.append((VExamInfo.ename.like(f'%{ename}%')))

        if start_time and len(start_time) >= 2:
            query.append((VExamInfo.start.between(start_time[0], start_time[1])))
        if create_times and len(create_times) >= 2:
            query.append((VExamInfo.create_time.between(create_times[0], create_times[1])))
        result = VExamInfo.query.filter(*query).paginate(int(page) + 1, per_page=int(size),
                                                         error_out=False)
        return result

    @staticmethod
    def query_all_options():
        choiceOpts = {
            'courseIds': [],
            'sessionIds': [],
            'resourceIds': [],
        }
        # 获取系统中的课程
        courses = VCourse.query.all()
        for course in courses:
            keyv = {
                'label': '{}_classId:{}'.format(course.cname, course.teachclass),
                'value': course.id
            }
            choiceOpts.get("courseIds").append(keyv)
        # 获取学期
        sessionIds = Session.query.order_by(Session.create_time).all()
        for sessionId in sessionIds:
            keyv = {
                'label': sessionId.session,
                'value': sessionId.id
            }
            choiceOpts.get("sessionIds").append(keyv)
        resourceIds = Room.query.all()
        for resourceId in resourceIds:
            keyv = {
                'label': resourceId.roomname,
                'value': resourceId.id
            }
            choiceOpts.get("resourceIds").append(keyv)
        return choiceOpts

    @staticmethod
    def create(curr_exam: ExamInfoTable):
        coursetable: ExamInfoTable = ExamInfoTable.query.filter(ExamInfoTable.ename == curr_exam.ename).one_or_none()
        if coursetable:
            raise AppException(f'{curr_exam.ename}已存在!')
        curr_exam.create_time = datetime.datetime.now()
        examInfotable = ExamInfoTable(
            ename=curr_exam.ename,
            totaltime=curr_exam.totaltime,
            score=curr_exam.score,
            start=curr_exam.start,
            end=curr_exam.end,
            resourceId=curr_exam.resourceId,
            sessionId=curr_exam.sessionId,
            courseId=curr_exam.courseId,
            create_time=curr_exam.create_time,
            create_by=curr_exam.create_by
        )
        db.session.add(examInfotable)
        db.session.commit()

    @staticmethod
    def find_by_id(id):
        examinfotable = db.session.query(ExamInfoTable).filter(ExamInfoTable.id == id).one_or_none()
        if examinfotable is None:
            raise AppException(f'您所操作的对象已不存在!')
        return examinfotable

    @staticmethod
    def delete(exam_set):
        if exam_set:
            for examId in exam_set:
                db.session.delete(examId)
            db.session.commit()

    @staticmethod
    def update(curr_exam: ExamInfoTable):
        examinfotable = ExamInfoTable.query.filter(ExamInfoTable.id == curr_exam.id).one_or_none()
        if examinfotable is None:
            raise AppException(f'修改的数据可能已不存在!')
        examinfotable.ename = curr_exam.ename
        examinfotable.score = curr_exam.score
        examinfotable.courseId = curr_exam.courseId
        examinfotable.sessionId = curr_exam.sessionId
        examinfotable.resourceId = curr_exam.resourceId
        examinfotable.totaltime = curr_exam.totaltime
        examinfotable.start = curr_exam.start
        examinfotable.end = curr_exam.end
        examinfotable.update_time = datetime.datetime.now()
        examinfotable.update_by = curr_exam.update_by
        db.session.commit()

    @staticmethod
    def query_deptId_SessionId(jsonData):
        deptId = jsonData.get('deptId')
        sessionId = jsonData.get('sessionId')
        vexaminfo = VExamInfo.query.filter(VExamInfo.teachclass == deptId, VExamInfo.sessionId == sessionId).paginate(
            int(0) + 1, per_page=int(1000),
            error_out=False)
        return vexaminfo
